package com.zjz.demo.PC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: zjz
 * @Date: 2021/10/08/13:11
 * @Description: 一个加1, 一个减  通知,等待,唤醒  -- 生产者通知有货了,等待,唤醒   消费者通知没货了,等待,唤醒
 * @Target: 生产者, 没有了就生产东西.
 */
public class Product1 {
    public static void main(String[] args) {
        Data1 data = new Data1();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();




        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"C").start();



        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"D").start();




    }

}

// 判断等待,业务,通知
class Data1{  // 数字,资源类
    private int num = 0;


    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    // +1
    public  void increment() throws InterruptedException {

        try {
            lock.lock();
            // 业务代码
            while (num!=0){
                // 等待
                condition.await();
                // 业务
                System.out.println(Thread.currentThread().getName()+"==>"+num);
            }
            num++;
            // 通知其它线程
            condition.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    // -1

    public  void decrement() throws InterruptedException {


        try {
            lock.lock();
            while (num==0){
                // 等待
                condition.await();
                // 业务
                System.out.println(Thread.currentThread().getName()+"==>"+num);
            }
            num--;

            // 通知
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }


}
